import 'package:flutter/material.dart';
import '../screens/home_screen.dart';
import '../screens/record_screen.dart';
import '../screens/history_screen.dart';
import '../screens/analytics_screen.dart';
import '../screens/settings_screen.dart';
import '../screens/mood_detail_screen.dart';
import '../screens/onboarding_screen.dart';
import '../screens/splash_screen.dart';
import '../screens/main_screen.dart';

/// 应用路由配置
/// 管理所有页面的路由导航
class AppRoutes {
  // 私有构造函数，防止实例化
  AppRoutes._();

  // ==================== 路由名称常量 ====================
  
  /// 启动页
  static const String splash = '/splash';
  
  /// 引导页
  static const String onboarding = '/onboarding';
  
  /// 主导航页面（底部导航）
  static const String main = '/main';
  
  /// 主页
  static const String home = '/home';
  
  /// 记录页面
  static const String record = '/record';
  
  /// 历史记录页面
  static const String history = '/history';
  
  /// 趋势分析页面
  static const String analytics = '/analytics';
  
  /// 设置页面
  static const String settings = '/settings';
  
  /// 情绪详情页面
  static const String moodDetail = '/mood-detail';
  
  // ==================== 路由表 ====================
  
  /// 路由表映射
  static Map<String, WidgetBuilder> get routes => {
    splash: (context) => const SplashScreen(),
    onboarding: (context) => const OnboardingScreen(),
    main: (context) => const MainScreen(),
    home: (context) => const HomeScreen(),
    record: (context) => const RecordScreen(),
    history: (context) => const HistoryScreen(),
    analytics: (context) => const AnalyticsScreen(),
    settings: (context) => const SettingsScreen(),
  };
  
  /// 初始路由
  static const String initialRoute = splash;
  
  // ==================== 路由生成器 ====================
  
  /// 路由生成器
  /// 处理带参数的路由和未定义的路由
  static Route<dynamic>? onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case moodDetail:
        // 情绪详情页面，需要传递记录ID参数
        final args = settings.arguments as Map<String, dynamic>?;
        if (args != null && args.containsKey('recordId')) {
          return MaterialPageRoute(
            builder: (context) => MoodDetailScreen(
              recordId: args['recordId'] as String,
            ),
            settings: settings,
          );
        }
        return _errorRoute(settings);
        
      default:
        // 检查是否在静态路由表中
        if (routes.containsKey(settings.name)) {
          return MaterialPageRoute(
            builder: routes[settings.name]!,
            settings: settings,
          );
        }
        return _errorRoute(settings);
    }
  }
  
  /// 错误路由
  /// 当路由不存在时显示的页面
  static Route<dynamic> _errorRoute(RouteSettings settings) {
    return MaterialPageRoute(
      builder: (context) => Scaffold(
        appBar: AppBar(
          title: const Text('页面不存在'),
          backgroundColor: Colors.red,
          foregroundColor: Colors.white,
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.red,
              ),
              const SizedBox(height: 16),
              Text(
                '页面不存在: ${settings.name}',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pushNamedAndRemoveUntil(
                    home,
                    (route) => false,
                  );
                },
                child: const Text('返回首页'),
              ),
            ],
          ),
        ),
      ),
      settings: settings,
    );
  }
  
  // ==================== 导航辅助方法 ====================
  
  /// 导航到指定页面
  /// [context] 上下文
  /// [routeName] 路由名称
  /// [arguments] 路由参数
  static Future<T?> navigateTo<T extends Object?>(
    BuildContext context,
    String routeName, {
    Object? arguments,
  }) {
    return Navigator.of(context).pushNamed(
      routeName,
      arguments: arguments,
    );
  }
  
  /// 替换当前页面
  /// [context] 上下文
  /// [routeName] 路由名称
  /// [arguments] 路由参数
  static Future<T?> replaceTo<T extends Object?, TO extends Object?>(
    BuildContext context,
    String routeName, {
    Object? arguments,
    TO? result,
  }) {
    return Navigator.of(context).pushReplacementNamed(
      routeName,
      arguments: arguments,
      result: result,
    );
  }
  
  /// 清空路由栈并导航到指定页面
  /// [context] 上下文
  /// [routeName] 路由名称
  /// [arguments] 路由参数
  static Future<T?> navigateAndClearStack<T extends Object?>(
    BuildContext context,
    String routeName, {
    Object? arguments,
  }) {
    return Navigator.of(context).pushNamedAndRemoveUntil(
      routeName,
      (route) => false,
      arguments: arguments,
    );
  }
  
  /// 返回上一页
  /// [context] 上下文
  /// [result] 返回结果
  static void goBack<T extends Object?>(BuildContext context, [T? result]) {
    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop(result);
    }
  }
  
  /// 返回到指定页面
  /// [context] 上下文
  /// [routeName] 目标路由名称
  static void popUntil(BuildContext context, String routeName) {
    Navigator.of(context).popUntil(ModalRoute.withName(routeName));
  }
  
  /// 检查是否可以返回
  /// [context] 上下文
  static bool canPop(BuildContext context) {
    return Navigator.of(context).canPop();
  }
  
  // ==================== 特殊导航方法 ====================
  
  /// 导航到情绪详情页面
  /// [context] 上下文
  /// [recordId] 记录ID
  static Future<void> navigateToMoodDetail(
    BuildContext context,
    String recordId,
  ) {
    return navigateTo(
      context,
      moodDetail,
      arguments: {'recordId': recordId},
    );
  }
  
  /// 导航到记录页面（编辑模式）
  /// [context] 上下文
  /// [recordId] 要编辑的记录ID
  static Future<void> navigateToEditRecord(
    BuildContext context,
    String recordId,
  ) {
    return navigateTo(
      context,
      record,
      arguments: {'editRecordId': recordId},
    );
  }
  
  /// 导航到主页面（清空路由栈）
  /// [context] 上下文
  static Future<void> navigateToHome(BuildContext context) {
    return navigateAndClearStack(context, home);
  }
  
  /// 导航到引导页面（清空路由栈）
  /// [context] 上下文
  static Future<void> navigateToOnboarding(BuildContext context) {
    return navigateAndClearStack(context, onboarding);
  }
  
  // ==================== 页面转场动画 ====================
  
  /// 创建淡入淡出转场动画
  /// [child] 目标页面
  /// [settings] 路由设置
  static PageRouteBuilder<T> createFadeTransition<T>(
    Widget child,
    RouteSettings settings,
  ) {
    return PageRouteBuilder<T>(
      settings: settings,
      pageBuilder: (context, animation, secondaryAnimation) => child,
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        return FadeTransition(
          opacity: animation,
          child: child,
        );
      },
      transitionDuration: const Duration(milliseconds: 300),
    );
  }
  
  /// 创建滑动转场动画
  /// [child] 目标页面
  /// [settings] 路由设置
  /// [direction] 滑动方向
  static PageRouteBuilder<T> createSlideTransition<T>(
    Widget child,
    RouteSettings settings, {
    SlideDirection direction = SlideDirection.fromRight,
  }) {
    return PageRouteBuilder<T>(
      settings: settings,
      pageBuilder: (context, animation, secondaryAnimation) => child,
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        Offset begin;
        switch (direction) {
          case SlideDirection.fromLeft:
            begin = const Offset(-1.0, 0.0);
            break;
          case SlideDirection.fromRight:
            begin = const Offset(1.0, 0.0);
            break;
          case SlideDirection.fromTop:
            begin = const Offset(0.0, -1.0);
            break;
          case SlideDirection.fromBottom:
            begin = const Offset(0.0, 1.0);
            break;
        }
        
        const end = Offset.zero;
        const curve = Curves.easeInOut;
        
        final tween = Tween(begin: begin, end: end);
        final curvedAnimation = CurvedAnimation(
          parent: animation,
          curve: curve,
        );
        
        return SlideTransition(
          position: tween.animate(curvedAnimation),
          child: child,
        );
      },
      transitionDuration: const Duration(milliseconds: 300),
    );
  }
}

/// 滑动方向枚举
enum SlideDirection {
  fromLeft,
  fromRight,
  fromTop,
  fromBottom,
}